<template>
  <!-- 添加或修改生产记录对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产日期" prop="produceDate">
              <el-date-picker clearable
                              v-model="form.produceDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择生产日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提交日期" prop="submitDate">
              <el-date-picker clearable
                              v-model="form.submitDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择提交日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
    </el-form>

    <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
              :max-height="tableMaxHeight" @sort-change="handleSortChange">

      <el-table-column align="center" prop="count" label="序号" width="150">
        <template slot-scope="scope">
          <el-input-number size="mini" v-model="scope.row.sort"></el-input-number>
        </template>
      </el-table-column>

      <el-table-column prop="goodsBrand" label="物料选择" width="300">
        <template slot-scope="scope">
          <el-autocomplete style="width: 280px;"
                           v-model="scope.row.goodsBrand"
                           :fetch-suggestions="querySearch"
                           placeholder="请输入内容"
          >
            <template #default="{ item, index }">
              <div @click="handleClick(item, scope.$index,scope.row)">
                {{ item.value }}
              </div>
            </template>
          </el-autocomplete>
        </template>
      </el-table-column>
      <el-table-column prop="goodsCode" label="存货编码" width="100" />
      <el-table-column prop="goodsModel" label="存货型号" width="100"/>
      <el-table-column prop="count" label="产品数量" width="150">
        <template slot-scope="scope">
          <el-input-number size="mini" v-model="scope.row.count"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="douser" label="操作工" width="150">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.douser"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="doremark" label="自制明细" >
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.doremark"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="douser" label="备注" width="150">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.remark"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-popconfirm :title="`确认删除当前数据项？`" @confirm="handleDelete(scope.row,scope.$index)"
                         style="margin-left: 10px;">
            <el-button slot="reference" size="mini" type="text" icon="el-icon-delete"
                       v-hasPermi="['develop:GoodsSaleMaterial:remove']">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-row>
      <el-col :span="24" style="text-align: center;padding-top: 20px;">
        <el-button style="width: 100%;" icon="el-icon-plus" plain type="primary" @click="addRow">添加行</el-button>
      </el-col>
    </el-row>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {addAction, deleteAction, getAction, getById, isEmpty, updateAction} from '@/api/manage';
import moment from 'moment';

export default {
  name: "ProduceRecordDetailListForm",
  data() {
    return {
      // 遮罩层
      loading: true,
      activeName: "first",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      dataList: [],
      goodsList: [],
      tableMaxHeight: window.innerHeight - 320,
      // 表单校验
      rules: {
        produceDate: [
          {required: true, message: "生产日期不能为空", trigger: "blur"}
        ],
        submitDate: [
          {required: true, message: "提交日期不能为空", trigger: "blur"}
        ],

      },
      queryParams:{
        produceId:null,
        orderByColumn: 'a.sort',
        isAsc: "asc",
        pageSizeZero:"true"
      },
      goodsQueryParams:{
        pageNum: 1,
        pageSize: 50,
        model: null,
        queryLabel:null
      },
      url: {
        getById: '/produceRecord/produceRecord/',
        add: '/produceRecord/produceRecord/add',
        edit: '/produceRecord/produceRecord/edit',
        detailList: '/produceRecordDetail/produceRecordDetail/list',
        remove: '/produceRecordDetail/produceRecordDetail/',
      },
    };
  },
  created() {

  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        nos: null,
        produceDate: null,
        submitDate: null,
        status: "0",
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.dataList=[];
      this.open = true;
      this.title = "添加生产记录单";
      for (let i = 0; i < 1; i++) {
        this.dataList.push({
          goodsId: '',//产品编号
          goodsCode: '',//产品编号
          goodsName: '',//名称
          goodModel: '',
          sort: i+1,
          count: 0
        })
      }
      this.loading = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.queryParams.produceId = row.id;
      this.getList();
      const id = row.id || this.ids;
      getById(this.url.getById, id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改生产记录单（"+row.nos+"）";
      });
    },

    /** 查询销售信息管理列表 */
    getList() {
      this.loading = true;
      getAction(this.url.detailList, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.loading = false;
        if (this.dataList.length === 0) {
          for (let i = 0; i < 1; i++) {
            this.dataList.push({
              goodsId: '',//产品编号
              code: '',//产品编号
              goodsName: '',//名称
              goodModel: '',
              daohuoCount: 0
            })
          }
        }else {
          for (let i = 0; i < this.dataList.length; i++) {
            this.dataList[i].goodsBrand = this.dataList[i].goodsName + '-' + this.dataList[i].goodsModel + '-' + this.dataList[i].goodsCode;
          }
        }

      });
    },


    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    getGoodsList() {
      getAction('/goodsOrderIn/goodsOrderIn/list', this.goodsQueryParams).then(response => {
        this.goodsList = response.rows;
        for (let i = 0; i < this.goodsList.length; i++) {
          // this.goodsList[i].label = this.goodsList[i].name + '-' + this.goodsList[i].model + '-' + this.goodsList[i].code;
          this.goodsList[i].value = this.goodsList[i].name + '-' + this.goodsList[i].model + '-' + this.goodsList[i].code;
        }
      })
    },

    querySearch(queryLabel, cb) {
      let that = this;
      that.goodsQueryParams.queryLabel= queryLabel;
      getAction('/goodsOrderIn/goodsOrderIn/list', that.goodsQueryParams).then(response => {
        that.goodsList = response.rows;
        for (let i = 0; i < this.goodsList.length; i++) {
          that.goodsList[i].value = that.goodsList[i].name + '-' + that.goodsList[i].model + '-' + that.goodsList[i].code;
        }
        const goodsList = that.goodsList;
        const results = queryLabel
          ? goodsList.filter(that.createFilter(queryLabel))
          : goodsList;
        // 调用 callback 返回建议列表的数据
        cb(results);
      })
    },

    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().includes(queryString.toLowerCase())
        );
      };
    },

    handleClick(item, index,row) {
      this.$nextTick(() => {
        let newItem = {
          goodsId: item.id,
          goodsCode: item.code, //产品编号
          goodsName: item.name, //名称
          goodsModel: item.model,//型号
          goodsUnit: item.unit, // 单位
          sort: row.sort, // 排序
          count: "0"
        }
        this.$set(this.dataList, index, newItem)
      })
    },

    //点击按钮添加空行
    addRow() {
      this.$nextTick(() => {
        this.dataList.push({
          goodsCode: '',//产品编号
          goodsName: '',//名称
          goodModel: '',
          sort: this.dataList.length+1,
          count: 0
        })
      })
    },

    /** 提交按钮 */
    submitForm() {
      let arrays = this.dataList;
      for (let i = 0; i < arrays.length; i++) {
        if (arrays[i].count === 0) {
          this.$modal.msgError(arrays[i].goodsName + "数量不能为0");
          return;
        }
        if (isEmpty(arrays[i].goodsId)) {
          this.$modal.msgError("序号："+arrays[i].sort + "请选择产品");
          return;
        }
      }
      this.form.detailList = this.dataList;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAction(this.url.edit, this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$emit('ok');
            });
          } else {
            addAction(this.url.add, this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$emit('ok');
            });
          }
        }
      });
    },


    handleDelete(row,index) {
      const ids = row.id || this.ids;
      if(isEmpty(ids)){
        this.$nextTick(() => {
          this.dataList.splice(index, 1)
        })
      }else{
        deleteAction(this.url.remove, ids).then(response => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      }
    },








  }
};
</script>
